import { Byte } from '../../api/io/Byte';
import { HashMap } from '../../api/struct/HashMap';
import { ShopItem } from './ShopItem';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';
import { MathUtils } from '../../api/math/MathUtils';



/**属性枚举*/
export const enum E_Shop {
	/**商城id*/
	SHOP_ID = 0,
	/**商品*/
	ITEM = 1,
	/**刷新次数重置时间*/
	LAST_RESET_REFRESH_TIME = 2,
	/**已使用刷新次数- 消耗*/
	COST_REFRESH_USE = 3,
	/**已使用刷新次数- 免费*/
	FREE_REFRESH_USE = 4,
	/**免费刷新次数自增数*/
	FREE_REFRESH_AUTO_ADD = 5,
	/**刷新次数自增开始计算时间*/
	FREE_REFRESH_AUTO_ADD_START_TIME = 6,
	/**枚举数量*/
	EnumCount = 7
}


/***/
export class Shop {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_SHOP_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_SHOP_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: Shop[] = [];

	/**创建入口*/
	public static create(json?: string): Shop {
		const c = this.POOL.pop() || new Shop();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**商城id (uint32)*/
	protected _shopId: number;
	/**商品*/
	protected _item: HashMap<number, ShopItem> = null;
	/**刷新次数重置时间 (long)*/
	protected _lastResetRefreshTime: number;
	/**已使用刷新次数- 消耗 (uint16)*/
	protected _costRefreshUse: number;
	/**已使用刷新次数- 免费 (uint16)*/
	protected _freeRefreshUse: number;
	/**免费刷新次数自增数 (uint16)*/
	protected _freeRefreshAutoAdd: number;
	/**刷新次数自增开始计算时间 (long)*/
	protected _freeRefreshAutoAddStartTime: number;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (Shop.POOL.indexOf(this) === -1) {
			Shop.POOL.push(this);
		}
	}

	/**商城id*/
	public get shopId() {
		return this._shopId;
	}


	/**商城id*/
	public set shopId(v: number) {
		this._shopId = v;
	}


	/**设置商品*/
	public putItem(k: number, v: ShopItem): ShopItem {
		const ov = this._item.put(k, v);
		return ov;
	}


	/**获取商品*/
	public getItem(k: number) {
		return this._item.get(k);
	}


	/**删除商品*/
	public removeItem(k: number, autoDestroy = false): ShopItem {
		const ov = this._item.remove(k);
		if (autoDestroy && ov) {
			ov.destroy();
		}
		return ov;
	}


	/**获取商品映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getItemKeys(): number[] {
		return this._item.getKeys();
	}


	/**获取商品映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getItemValues(): ShopItem[] {
		return this._item.getValues();
	}


	/**清空商品映射表*/
	public clearItemMap(autoDestroy = false): void {
		const ks = this._item.getKeys();
		for (let i = ks.length - 1; i >= 0; i--) {
			this.removeItem(ks[i], autoDestroy);
		}
	}


	/**刷新次数重置时间*/
	public get lastResetRefreshTime() {
		return this._lastResetRefreshTime;
	}


	/**刷新次数重置时间*/
	public set lastResetRefreshTime(v: number) {
		this._lastResetRefreshTime = v;
	}


	/**已使用刷新次数- 消耗*/
	public get costRefreshUse() {
		return this._costRefreshUse;
	}


	/**已使用刷新次数- 消耗*/
	public set costRefreshUse(v: number) {
		this._costRefreshUse = v;
	}


	/**已使用刷新次数- 免费*/
	public get freeRefreshUse() {
		return this._freeRefreshUse;
	}


	/**已使用刷新次数- 免费*/
	public set freeRefreshUse(v: number) {
		this._freeRefreshUse = v;
	}


	/**免费刷新次数自增数*/
	public get freeRefreshAutoAdd() {
		return this._freeRefreshAutoAdd;
	}


	/**免费刷新次数自增数*/
	public set freeRefreshAutoAdd(v: number) {
		this._freeRefreshAutoAdd = v;
	}


	/**刷新次数自增开始计算时间*/
	public get freeRefreshAutoAddStartTime() {
		return this._freeRefreshAutoAddStartTime;
	}


	/**刷新次数自增开始计算时间*/
	public set freeRefreshAutoAddStartTime(v: number) {
		this._freeRefreshAutoAddStartTime = v;
	}



	/**通过枚举获取值*/
	public getV(k: E_Shop): any {
		switch (k) {
			case E_Shop.SHOP_ID: return this._shopId;
			case E_Shop.ITEM: return this._item;
			case E_Shop.LAST_RESET_REFRESH_TIME: return this._lastResetRefreshTime;
			case E_Shop.COST_REFRESH_USE: return this._costRefreshUse;
			case E_Shop.FREE_REFRESH_USE: return this._freeRefreshUse;
			case E_Shop.FREE_REFRESH_AUTO_ADD: return this._freeRefreshAutoAdd;
			case E_Shop.FREE_REFRESH_AUTO_ADD_START_TIME: return this._freeRefreshAutoAddStartTime;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_Shop, v: any): void {
		switch (k) {
			case E_Shop.SHOP_ID: this._shopId = v; break;
			case E_Shop.ITEM: this._item = v; break;
			case E_Shop.LAST_RESET_REFRESH_TIME: this._lastResetRefreshTime = v; break;
			case E_Shop.COST_REFRESH_USE: this._costRefreshUse = v; break;
			case E_Shop.FREE_REFRESH_USE: this._freeRefreshUse = v; break;
			case E_Shop.FREE_REFRESH_AUTO_ADD: this._freeRefreshAutoAdd = v; break;
			case E_Shop.FREE_REFRESH_AUTO_ADD_START_TIME: this._freeRefreshAutoAddStartTime = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//商城id
		this._shopId = 0;
		//商品
		if (this._item) {
			const list = this._item.getValues();
			for (let i = 0, len = list.length; i < len; i++) {
				list[i].destroy();
			}
			this._item.clear();
		}
		else {
			this._item = new HashMap<number, ShopItem>();
		}
		//刷新次数重置时间
		this._lastResetRefreshTime = 0;
		//已使用刷新次数- 消耗
		this._costRefreshUse = 0;
		//已使用刷新次数- 免费
		this._freeRefreshUse = 0;
		//免费刷新次数自增数
		this._freeRefreshAutoAdd = 0;
		//刷新次数自增开始计算时间
		this._freeRefreshAutoAddStartTime = 0;
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._shopId) {
			json.shopId = this._shopId;
		}
		if (this._item.size() > 0) {
			const ks = this._item.getKeys();
			const vs = this._item.getValues();
			const list: string[] = [];
			for (let i = 0, len = vs.length; i < len; i++) {
				list[i] = vs[i].stringify(false);
			}
			json.item = [ks, list];
		}
		if (this._lastResetRefreshTime) {
			json.lastResetRefreshTime = this._lastResetRefreshTime;
		}
		if (this._costRefreshUse) {
			json.costRefreshUse = this._costRefreshUse;
		}
		if (this._freeRefreshUse) {
			json.freeRefreshUse = this._freeRefreshUse;
		}
		if (this._freeRefreshAutoAdd) {
			json.freeRefreshAutoAdd = this._freeRefreshAutoAdd;
		}
		if (this._freeRefreshAutoAddStartTime) {
			json.freeRefreshAutoAddStartTime = this._freeRefreshAutoAddStartTime;
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.shopId) {
			this._shopId = json.shopId;
		}
		if (json.item) {
			const ks: number[] = json.item[0] || (json.item.getKeys ? json.item.getKeys() : null);	//对象可能是json或者结构体
			const vs: string[] = json.item[1] || (json.item.getValues ? json.item.getValues() : null);
			if (ks && vs && ks.length === vs.length) {
				for (let i = 0, len = vs.length; i < len; i++) {
					this._item.put(ks[i], ShopItem.create(vs[i]));
				}
			}
		}
		if (json.lastResetRefreshTime) {
			this._lastResetRefreshTime = json.lastResetRefreshTime;
		}
		if (json.costRefreshUse) {
			this._costRefreshUse = json.costRefreshUse;
		}
		if (json.freeRefreshUse) {
			this._freeRefreshUse = json.freeRefreshUse;
		}
		if (json.freeRefreshAutoAdd) {
			this._freeRefreshAutoAdd = json.freeRefreshAutoAdd;
		}
		if (json.freeRefreshAutoAddStartTime) {
			this._freeRefreshAutoAddStartTime = json.freeRefreshAutoAddStartTime;
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		byte.writeUint32(this._shopId);
		//商品
		{
			const ks = this._item.getKeys();
			const vs = this._item.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeUint32(ks[i]);
				vs[i].toBytes(byte);
			}
		}
		byte.writeLongNumber(this._lastResetRefreshTime);
		byte.writeUint16(this._costRefreshUse);
		byte.writeUint16(this._freeRefreshUse);
		byte.writeUint16(this._freeRefreshAutoAdd);
		byte.writeLongNumber(this._freeRefreshAutoAddStartTime);
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._shopId = byte.readUint32();
		//商品
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readUint32();
				const v = ShopItem.create();
				v.fromBytes(byte);
				this._item.put(k, v);
			}
		}
		this._lastResetRefreshTime = byte.readLongNumber();
		this._costRefreshUse = byte.readUint16();
		this._freeRefreshUse = byte.readUint16();
		this._freeRefreshAutoAdd = byte.readUint16();
		this._freeRefreshAutoAddStartTime = byte.readLongNumber();
		return this;
	}


	/**克隆*/
	public clone(): Shop {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = Shop.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = Shop.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//商城id
			if (idx === E_Shop.SHOP_ID) {
				const oldv = this._shopId;
				this._shopId = us[i + 1];
				IAsync.dispatch(eventID, idx, this._shopId, oldv);
				i += 2;
				continue;
			}

			//商品
			if (idx === E_Shop.ITEM) {
				const k: number = us[i + 1];
				const ctrl: number = us[i + 2];
				if (ctrl === 0) {
					const oldv = this.removeItem(k);
					if (oldv) {
						oldv.destroy()
					}
				}
				else if (ctrl === 1) {
					const newv = ShopItem.create(us[i + 3]);
					const oldv = this.putItem(k, newv);
					if (oldv) {
						oldv.destroy()
					}
				}
				else {
					const curv = this.getItem(k);
					if (curv) {
						curv.processUpdate(us[i + 3]);
					}
					else {
						console.error('Shop ShopItem is not exist when update! k = ' + k);
					}
				}
				IAsync.dispatch(eventID, idx, k, ctrl);
				i += ctrl === 0 ? 3 : 4;
				continue;
			}
			//刷新次数重置时间
			if (idx === E_Shop.LAST_RESET_REFRESH_TIME) {
				const oldv = this._lastResetRefreshTime;
				this._lastResetRefreshTime = us[i + 1];
				IAsync.dispatch(eventID, idx, this._lastResetRefreshTime, oldv);
				i += 2;
				continue;
			}
			//已使用刷新次数- 消耗
			if (idx === E_Shop.COST_REFRESH_USE) {
				const oldv = this._costRefreshUse;
				this._costRefreshUse = us[i + 1];
				IAsync.dispatch(eventID, idx, this._costRefreshUse, oldv);
				i += 2;
				continue;
			}
			//已使用刷新次数- 免费
			if (idx === E_Shop.FREE_REFRESH_USE) {
				const oldv = this._freeRefreshUse;
				this._freeRefreshUse = us[i + 1];
				IAsync.dispatch(eventID, idx, this._freeRefreshUse, oldv);
				i += 2;
				continue;
			}
			//免费刷新次数自增数
			if (idx === E_Shop.FREE_REFRESH_AUTO_ADD) {
				const oldv = this._freeRefreshAutoAdd;
				this._freeRefreshAutoAdd = us[i + 1];
				IAsync.dispatch(eventID, idx, this._freeRefreshAutoAdd, oldv);
				i += 2;
				continue;
			}
			//刷新次数自增开始计算时间
			if (idx === E_Shop.FREE_REFRESH_AUTO_ADD_START_TIME) {
				const oldv = this._freeRefreshAutoAddStartTime;
				this._freeRefreshAutoAddStartTime = us[i + 1];
				IAsync.dispatch(eventID, idx, this._freeRefreshAutoAddStartTime, oldv);
				i += 2;
				continue;
			}

			console.error('[Struct Data] can not find enum in Shop with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: Shop): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		if (this._shopId !== other._shopId) {
			updates.push(E_Shop.SHOP_ID, this._shopId);
		}

		//商品
		{
			const idx = E_Shop.ITEM;
			const ks1 = this._item.getKeys();
			const ks2 = other._item.getKeys();
			const rs = MathUtils.intersectSortedArray(ks1, ks2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getItem(k);
					const oldv = other.getItem(k);
					const ui = newv.getCompareInfo(oldv);
					if (ui && ui.length > 0) {
						updates.push(idx, k, 2, ui);
					}
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getItem(k);
					updates.push(idx, k, 1, newv.stringify(false));
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}
		if (this._lastResetRefreshTime !== other._lastResetRefreshTime) {
			updates.push(E_Shop.LAST_RESET_REFRESH_TIME, this._lastResetRefreshTime);
		}
		if (this._costRefreshUse !== other._costRefreshUse) {
			updates.push(E_Shop.COST_REFRESH_USE, this._costRefreshUse);
		}
		if (this._freeRefreshUse !== other._freeRefreshUse) {
			updates.push(E_Shop.FREE_REFRESH_USE, this._freeRefreshUse);
		}
		if (this._freeRefreshAutoAdd !== other._freeRefreshAutoAdd) {
			updates.push(E_Shop.FREE_REFRESH_AUTO_ADD, this._freeRefreshAutoAdd);
		}
		if (this._freeRefreshAutoAddStartTime !== other._freeRefreshAutoAddStartTime) {
			updates.push(E_Shop.FREE_REFRESH_AUTO_ADD_START_TIME, this._freeRefreshAutoAddStartTime);
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(Shop.TOTAL_EVENT_ID, this.getV(0));
	}

}
